import { message } from 'antd'
import type { RcFile, UploadFile } from 'antd/es/upload'
import { InboxOutlined } from '@ant-design/icons'

import { fileValidate } from '@/utils/utils'

interface IProcessedFile {
  file: RcFile
  name: string // 纯名称
  ext: string // 包含点的纯小写后缀
  fullName: string // 纯名称 + 包含点的纯小写后缀
}

export const accept = `${fileValidate.PDF_ACCEPT},${fileValidate.IMG_ACCEPT}`

export const getProcessedFileList = (
  pickFileList: RcFile[],
  repeatType: 'name' | 'fullName' = 'name',
): IProcessedFile[] => {
  const processedFileList: IProcessedFile[] = []

  pickFileList.forEach(file => {
    const match = file.name.match(/(.+)(\.\w+)$/)
    if (!match) return []

    const name = match[1]
    const ext = match[2].toLocaleLowerCase()
    const fullName = `${name}${ext}`

    const repeatIndex = processedFileList.findIndex(f => {
      if (repeatType === 'fullName') return f.fullName === fullName
      return f.name === name
    })
    if (repeatIndex > -1) {
      processedFileList.splice(repeatIndex, 1) // 去重
    }

    processedFileList.push({ file, name, ext, fullName })
  })

  return processedFileList
}

export const localValidate = (processedFileList: IProcessedFile[]): string | undefined => {
  if (!processedFileList.length) {
    return `选择的附件不符合命名规则`
  }
  return fileValidate(
    processedFileList.map(d => d.file),
    { accept, max: fileValidate.MAX },
  )
}

export const handleMsg = (processedFileList: IProcessedFile[]) => {
  let successNum = 0
  let failNum = 0
  processedFileList.forEach(({ file }) => {
    const target = file as unknown as UploadFile
    if (target.status === 'error') failNum++
    else successNum++
  })
  let msg = `本次上传`
  if (successNum > 0) msg += `，成功${successNum}个`
  if (failNum > 0) msg += `，失败${failNum}个`
  let msgFn = message.success
  if (failNum > 0) msgFn = message.warning
  msgFn(msg)
}

export const getUploadTrigger = () => (
  <>
    <p className="ant-upload-drag-icon">
      <InboxOutlined />
    </p>
    <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
    <p className="ant-upload-hint">
      支持单个或批量上传，单文件大小不能超过<b>{fileValidate.MAX}MB</b>，仅支持<b>pdf文档类与图片类</b>
    </p>
  </>
)
